package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;


import cn.edu.sdjzu.xg23.kcsj01_backend.entity.EmployeeAssTextbook;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Textbook;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.AbsAchievementMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.EmployeeAssTextbookMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.TextbookMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.TextbookService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class TextbookServiceImpl implements TextbookService {

    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Autowired
    private TextbookMapper textbookMapper;
    @Autowired
    private AbsAchievementMapper absAchievementMapper;
    @Autowired
    private EmployeeAssTextbookMapper employeeAssTextbookMapper;
    @Override
    @Transactional // 声明事务
    public boolean save(Textbook textbook) {
        Long sharedId = idGenerator.generateId();

        // 1. 插入 Achievement 相关记录
        absAchievementMapper.addAchievement(sharedId, "项目");

        // 2. 插入 Project 记录
        textbook.setId(sharedId);
        boolean success = textbookMapper.insert(textbook);
        boolean insertSuccess = false;
        if (success && textbook.getApplicants() != null && !textbook.getApplicants().isEmpty()) {
            for (EmployeeAssTextbook applicant : textbook.getApplicants()) {
                applicant.setTextbook(new Textbook(sharedId));// 设置专利关联
            }

            insertSuccess  = employeeAssTextbookMapper.insertApplicants(textbook.getApplicants());
        }
        return success&&insertSuccess;
    }

    @Override
    public  boolean deleteById(Long id) {
        return absAchievementMapper.deleteById(id);
    }

    @Override
    public void update(Textbook textbook) {
        textbookMapper.update(textbook);
    }


    @Override
    public PageInfo<Textbook> selectTextbooksByCondition(Integer pageNum, Integer pageSize, Textbook textbook, Long employeeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Textbook> textbookList = textbookMapper.selectTextbooksByCondition(textbook,employeeId);
        return new PageInfo<>(textbookList);
    }
    @Override
    public boolean approveTextbook(Textbook textbook) {
        return textbookMapper.approveTextbook(textbook);
    }
}